package cn.fl.upgrade.controller;

import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.comm.facade.upgrade.dto.SysAppVerRuleDTO;
import cmm.multi.redis.service.IMultiRedisService;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.upgrade.vo.SysAppVerRuleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.upgrade.condition.SysAppVerCfgQueryCondition;
import cmm.comm.facade.upgrade.dto.SysAppVerCfgDTO;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cmm.web.core.upgrade.UpgradeAppVerRec;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.constant.CacheConstant;
import cn.cmm.cache.framework.service.ICacheService;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.upgrade.service.ISysAppVerCfgService;
import cn.fl.upgrade.vo.SysAppVerCfgVO;
import fl.constant.facade.framework.constant.UpgradeConstant;

/**
 * @Description: 移动APP版本配置表 控制层
 */
@Controller
@RequestMapping("/upgrade/sysAppVerCfg")
public class SysAppVerCfgController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysAppVerCfgController.class);

	/**
	 * SysAppVerCfg 服务层BEAN
	 */
	@Autowired
	private ISysAppVerCfgService sysAppVerCfgService;
	
	/**
	 * 缓存服务
	 */
	@Autowired
	private ICacheService cacheService;

	/**
	 * 缓存集群服务
	 */
	@Resource(name = "userRedisService")
	private IMultiRedisService userRedisService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toSysAppVerCfgList.do", method = { RequestMethod.GET})
	public ModelAndView toSysAppVerCfgList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("upgrade/sysAppVerCfg/sysAppVerCfgList");
		List<KeyValueVO> syscdlist = this.sysAppVerCfgService.getKvListWithAttr1AndAttr2(DictionaryConstant.CODE_MGT_SYS_DS_CD,DictionaryConstant.CODE_SYS_CODE_ATTR2_CD,"",CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
		List<KeyValueVO> optypcdlist = this.sysAppVerCfgService.getKvList(DictionaryConstant.CODE_OP_TYP_CD, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("optypcdlist",optypcdlist);
		view.addObject("syscdlist",syscdlist);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifySysAppVerCfg.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifySysAppVerCfg(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("upgrade/sysAppVerCfg/modifySysAppVerCfg");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initSysAppVerCfgList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initSysAppVerCfgList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String sysCd = request.getParameter("sysCd");
		String opTypCd = request.getParameter("opTypCd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysAppVerCfgQueryCondition qc = new SysAppVerCfgQueryCondition();
		if (StringUtils.isNotEmpty(sysCd)) {
			qc.setSysCd(sysCd);
		}
		if (StringUtils.isNotEmpty(opTypCd)) {
			qc.setOpTypCd(opTypCd);
		}
		page.setCondition(qc);
		
		Pager pager = this.sysAppVerCfgService.searchListPage(page);
		List<SysAppVerCfgVO> list = (List<SysAppVerCfgVO>)pager.getResultList();
		for(SysAppVerCfgVO _vo : list){
			if(StringUtils.isNotEmpty(_vo.getSysCd())){
				Map<String,String> syscdmap = this.sysAppVerCfgService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd(),DictionaryConstant.CODE_MGT_SYS_DS_CD);
				_vo.setSysCd(syscdmap.get(_vo.getSysCd()));
			}
			if(StringUtils.isNotEmpty(_vo.getOpTypCd())){
				Map<String,String> optypmap = this.sysAppVerCfgService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd(),DictionaryConstant.CODE_OP_TYP_CD);
				_vo.setOpTypCd(optypmap.get(_vo.getOpTypCd()));
			}
			if(null != _vo.getIsForceUpdate()){
				Map<String,String> updatemap = new HashMap<String,String>();
				updatemap.put("0","不强制更新");
				updatemap.put("1","强制更新");
				_vo.setIsForceUpdateNm(updatemap.get(String.valueOf(_vo.getIsForceUpdate())));
			}
		}
		ListPageVO<SysAppVerCfgVO> listPage = new ListPageVO<SysAppVerCfgVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.sysAppVerCfgService.removeById(Long.valueOf(id));
			//同时删除缓存版本信息
			
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysAppVerCfgVO vo = this.sysAppVerCfgService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysAppVerCfgVO entity = null;
		String traceId = UUID.randomUUID().toString();

		try {
			entity = new SysAppVerCfgVO();
			Long id = this.sysAppVerCfgService.add(entity,traceId);
			result.setData(id);
			BaseLogUtils.info(logger, "add", traceId+"新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", traceId+"新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", traceId+"新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping(value = "/modifySysAppVerCfgPage.do", method = { RequestMethod.GET })
	@ResponseBody
	public ModelAndView modifySysAppVerCfgPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		ModelAndView view = new ModelAndView("upgrade/sysAppVerCfg/modifySysAppVerCfg");
		String id = request.getParameter("id");
		SysAppVerCfgVO entity = new SysAppVerCfgVO();
		if(StringUtils.isNotEmpty(id)){
			entity = this.sysAppVerCfgService.selectById(Long.valueOf(id));
			if(null != entity && null != entity.getRelDt()){
				entity.setRelDtStr(DateUtils.formatDateToString(entity.getRelDt(),DateUtils.YYYY_MM_DD));
			}
			if(null != entity && CollectionUtils.isNotEmpty(entity.getSysAppVerRuleVOList())){
				List<SysAppVerRuleVO> list=entity.getSysAppVerRuleVOList();
				SysAppVerRuleVO vo=list.get(0);
				entity.setVerRule(vo.getVerRule());
				entity.setVerType(vo.getVerType());
			}
		}
		if(null == entity){
			entity=new SysAppVerCfgVO();
		}
		if( null == entity.getRelDt()){
			entity.setRelDtStr(DateUtils.formatDateToString(new Date(),DateUtils.YYYY_MM_DD));
		}
		String sysCd = CurrentThreadContext.getFlServiceSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		List<KeyValueVO> syscdlist = this.sysAppVerCfgService.getKvListWithAttr1AndAttr2(DictionaryConstant.CODE_MGT_SYS_DS_CD,DictionaryConstant.CODE_SYS_CODE_ATTR2_CD,"", sysCd, orgCd);
		List<KeyValueVO> optypcdlist = this.sysAppVerCfgService.getKvList(DictionaryConstant.CODE_OP_TYP_CD, sysCd, orgCd);
		view.addObject("serverpath", PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
		view.addObject("optypcdlist",optypcdlist);
		view.addObject("syscdlist",syscdlist);
		view.addObject("sysappvercfg",entity);

		return view;
	}
	/**
	 * 修改
	 */
	@RequestMapping(value = "/modifySysAppVerCfg.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifySysAppVerCfg(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String traceId = UUID.randomUUID().toString();
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"modifySysAppVerCfg",traceId+"修改系统版本信息.请求时间：" + startTm + "-请求参数：" + this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName());

		String sysappId = request.getParameter("sysappId");
		String verDscr = request.getParameter("verDscr");
		String sysCd = request.getParameter("sysCd");
		String opTypCd = request.getParameter("opTypCd");
		String verId = request.getParameter("verId");
		String verNo = request.getParameter("verNo");
		String relDt = request.getParameter("relDt");
		String instFileUrl = request.getParameter("instFileUrl");
		String isForceUpdate = request.getParameter("isForceUpdate");
		String upgradeVerId = request.getParameter("upgradeVerId");
		String verType = request.getParameter("verType");
		String verRule = request.getParameter("verRule");
		DataResultVO result = null;
		SysAppVerCfgVO entity = null;
		try {

			entity = new SysAppVerCfgVO();

			if(StringUtils.isNotEmpty(verDscr)){
				entity.setVerDscr(verDscr);
			}
			if(StringUtils.isNotEmpty(sysCd)){
				entity.setSysCd(sysCd);
			}
			if(StringUtils.isNotEmpty(opTypCd)){
				entity.setOpTypCd(opTypCd);
			}
			if(StringUtils.isNotEmpty(verId)){
				entity.setVerId(Long.valueOf(verId));
			}
			if(StringUtils.isNotEmpty(verNo)){
				entity.setVerNo(verNo);
			}
			if(StringUtils.isNotEmpty(relDt)){
				entity.setRelDt(DateUtils.formatStringToDate(relDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(instFileUrl)){
				entity.setInstFileUrl(instFileUrl);
			}
			if(StringUtils.isNotEmpty(isForceUpdate)){
				entity.setIsForceUpdate(Integer.valueOf(isForceUpdate));
			}
			if (StringUtils.isNotEmpty(upgradeVerId)) {
				entity.setUpgradeVerId(upgradeVerId);
			}

			//强制更新
			if("1".equals(isForceUpdate)) {
				if(StringUtils.isNotEmpty(verType)){
					if(!"1".equals(verType) && StringUtils.isEmpty(verRule)){
						throw new BaseException("请输入版本号信息");
					}
				}else{
					throw new BaseException("请选择APP类型");
				}
			}
			List<SysAppVerRuleVO> ruleVOList=new ArrayList<>();
			SysAppVerRuleVO sysAppVerRuleVO=new SysAppVerRuleVO();
			sysAppVerRuleVO.setIsDel(BaseConstant.IS_YESNO_NO);
			sysAppVerRuleVO.setVerRule(verRule);
			sysAppVerRuleVO.setVerType(verType);
			ruleVOList.add(sysAppVerRuleVO);
			entity.setSysAppVerRuleVOList(ruleVOList);

//			if(StringUtils.isNotEmpty(strVerRuleList)){
//				List<SysAppVerRuleVO> ruleVOList = JSON.parseArray(strVerRuleList, SysAppVerRuleVO.class);
//				entity.setSysAppVerRuleVOList(ruleVOList);
//			}
			if(StringUtils.isNotEmpty(sysappId)){
				result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
				entity.setId(Long.valueOf(sysappId));
				entity.setMdfTm(new Date());
				entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				SysAppVerCfgQueryCondition condition = new SysAppVerCfgQueryCondition();
                condition.setVerId(entity.getVerId());
				List<SysAppVerCfgDTO> sysAppVerCfgDTOList = this.sysAppVerCfgService.searchList(condition);
				if (CollectionUtils.isNotEmpty(sysAppVerCfgDTOList)) {
					for (SysAppVerCfgDTO sysAppVerCfgDTO : sysAppVerCfgDTOList) {
						if (entity.getId().longValue() != sysAppVerCfgDTO.getId().longValue()) {
							result.setSuccess(BaseConstant.IS_YESNO_NO);
							result.setInfo("升级版本号已存在，请更换版本号！");
							BaseLogUtils.info(logger, "modifySysAppVerCfg", traceId+"升级版本号已存在，请更换版本号！");
							return result;
						}
					}
				}
				BaseLogUtils.info(logger,"modifySysAppVerCfg",traceId+"修改请求参数:"+JSON.toJSONString(entity));
				boolean success = this.sysAppVerCfgService.modify(entity,traceId);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
					BaseLogUtils.info(logger, "modifySysAppVerCfg", traceId+"修改失败.[id="+sysappId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				}else{
					this.addUpgradeVersToCache(opTypCd, sysCd);
				}


			}else{
				result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				SysAppVerCfgQueryCondition condition = new SysAppVerCfgQueryCondition();
				condition.setVerId(entity.getVerId());
				List<SysAppVerCfgDTO> sysAppVerCfgDTOList = this.sysAppVerCfgService.searchList(condition);
				if (CollectionUtils.isNotEmpty(sysAppVerCfgDTOList)) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
					BaseLogUtils.info(logger, "modifySysAppVerCfg", traceId+"升级版本号已存在，请更换版本号！");
					return result;
				}
				BaseLogUtils.info(logger,"modifySysAppVerCfg",traceId+"新增请求参数:"+JSON.toJSONString(entity));
				Long id = this.sysAppVerCfgService.add(entity,traceId);
				if(null == id){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
					BaseLogUtils.info(logger, "modifySysAppVerCfg", traceId+"新增失败.[id="+sysappId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				}else{
					this.addUpgradeVersToCache(opTypCd, sysCd);
				}
			}

		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifySysAppVerCfg", traceId+"修改失败.[id="+sysappId+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifySysAppVerCfg", traceId+"修改失败.[id="+sysappId+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"modifySysAppVerCfg",traceId+"修改系统版本信息.返回结果：" + JSON.toJSONString(result) + "-耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}
	/**
	 * 删除
	 */
	@RequestMapping(value = "/removeSysAppVerCfg.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object removeSysAppVerCfg(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String traceId = UUID.randomUUID().toString();

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeSysAppVerCfg", traceId+"删除数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysAppVerCfgVO entity = null;
		try {
			entity = new SysAppVerCfgVO();
			entity.setId(Long.valueOf(id));
			entity.setIsDel(1);
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.sysAppVerCfgService.modify(entity,traceId);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "modify", traceId+"删除数据失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}else{
				//删除缓存版本信息
				Boolean is = false;
				Boolean isusr = false;
				entity = this.sysAppVerCfgService.selectById(Long.valueOf(id));
				if(null != entity){
					String upgradesubkey = PropertiesCacheUtils.getProperty(UpgradeConstant.UPGRADE_VER_CACHE_MID_KEY);
					String delKey = entity.getSysCd() + upgradesubkey + entity.getOpTypCd();
					is = this.cacheService.delete(delKey, CacheConstant.CACHE_OPERATION_REMOTE);
					isusr = this.userRedisService.delete(delKey);
					BaseLogUtils.info(logger, "modify", traceId+"删除缓存is=" + is);
					BaseLogUtils.info(logger, "modify", traceId+"删除缓存isusr=" + isusr);
				}
				//同时插入删除后最新版的缓存
				if (is) {
					this.addUpgradeVersToCache(entity.getSysCd(), entity.getOpTypCd());
					BaseLogUtils.info(logger, "modify", traceId+"重新增加缓存");
				}
			}
			BaseLogUtils.info(logger, "removeSysAppVerCfg", traceId+"删除数据成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeSysAppVerCfg", traceId+"删除数据失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeSysAppVerCfg", traceId+"删除数据失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 添加最新更新版本到缓存
	 * @param opTypCd 客户端类型
	 * @param sysCd 系统代码
	 */
	private void addUpgradeVersToCache(String opTypCd, String sysCd){
		SysAppVerCfgDTO sysAppVerCfgDTO = null;
		try {
			SysAppVerCfgQueryCondition condition = new SysAppVerCfgQueryCondition();
			condition.setSysCd(sysCd);
			condition.setOpTypCd(opTypCd);
			sysAppVerCfgDTO = this.sysAppVerCfgService.getUpgradeAppVer(condition);
			if (null != sysAppVerCfgDTO) {
				String upgradesubkey = PropertiesCacheUtils.getProperty(UpgradeConstant.UPGRADE_VER_CACHE_MID_KEY);
				UpgradeAppVerRec upgradeAppVerRec = new UpgradeAppVerRec();
				upgradeAppVerRec.setOpTypCd(opTypCd);
				upgradeAppVerRec.setSysCd(sysCd);
				upgradeAppVerRec.setVerId(sysAppVerCfgDTO.getVerId());
				upgradeAppVerRec.setVerNo(sysAppVerCfgDTO.getVerNo());
				upgradeAppVerRec.setVerDscr(sysAppVerCfgDTO.getVerDscr());
				upgradeAppVerRec.setInstFileUrl(sysAppVerCfgDTO.getInstFileUrl());
				upgradeAppVerRec.setRelDt(sysAppVerCfgDTO.getRelDt());
				upgradeAppVerRec.setIsForceUpdate(sysAppVerCfgDTO.getIsForceUpdate());
				upgradeAppVerRec.setUpgradeVerId(sysAppVerCfgDTO.getUpgradeVerId());
				//设置老缓存
				this.cacheService.add(sysCd + upgradesubkey + opTypCd, upgradeAppVerRec, CacheConstant.CACHE_OPERATION_REMOTE);
				//设置集群缓存
				this.userRedisService.set(sysCd + upgradesubkey + opTypCd, upgradeAppVerRec);

				this.setAppMaxVerRule(opTypCd,sysCd);
			}
		}catch(BaseException ex) {
			BaseLogUtils.info(logger, "addUpgradeVersToCache", "更新最新版本到缓存错误BaseException->" + JSON.toJSONString(sysAppVerCfgDTO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			BaseLogUtils.error(logger, "addUpgradeVersToCache", "更新最新版本到缓存错误Exception->" + JSON.toJSONString(sysAppVerCfgDTO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
	}
	
	/**
	 * @throws IllegalStateException
	 * @throws IOException
	 * @Desc 文件上传(上传文件到阿里云)
	 * @Desc 系统相对路径前缀 + 系统代码 + 模块(自定义) + 时间 + 文件
	 */
	@RequestMapping(value = "/upload.do", method = { RequestMethod.POST })
	@ResponseBody
	public DataResultVO upload(
			// 上传多个文件
			MultipartHttpServletRequest multipartRequest, HttpServletRequest request, HttpServletResponse response)
			throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "上传成功");
		// 获取文件 存储位置
		String filePath = request.getParameter("filePath");// 前端传过来的文件模块路径
		String opTypCd = request.getParameter("opTypCd");
		String sysCd = request.getParameter("sysCd");
		String verNo = request.getParameter("verNo");
		if(StringUtils.isEmpty(opTypCd)){
			result.setInfo("请先选择app类型！");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		if(StringUtils.isEmpty(sysCd)){
			result.setInfo("请先选择系统！");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		if(StringUtils.isEmpty(verNo)){
			result.setInfo("请先填写版本号");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			return result;
		}
		try {			
			String ossPath = this.sysAppVerCfgService.uploadToOss(multipartRequest, sysCd,opTypCd,verNo);
			if(StringUtils.isNotEmpty(ossPath)){
				result.setData(ossPath);
				result.setInfo("上传成功");
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				BaseLogUtils.info(logger, "upload", "文件上传成功.FILEPATH:" + filePath + ".FILEPARAMS:" + ossPath,
						CurrentThreadContext.getCurrentUserName());
			}else{
				//result.setData(ossPath);
				result.setInfo("上传失败");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				BaseLogUtils.info(logger, "upload", "文件上传失败.FILEPATH:" + filePath + ".FILEPARAMS:" + ossPath,
						CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "upload", "文件上传失败.FILEPATH:" + filePath + ".ERROR",
					CurrentThreadContext.getCurrentUserName(), ex);
		} catch (IllegalStateException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误");
			BaseLogUtils.error(logger, "upload", "文件上传失败,系统错误.FILEPATH:" + filePath + ".ERROR",
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;

	}

	/**
	 * @MethodName getVerId
	 * @Description: TODO 获取升级版本号
	 * @Author: zhangxianchao@lionbridgecapital.cn
	 * @CreateDate: 2019/2/21 13:53
	 * @Version: 1.0.0
	 * @Param
	 * @Return cmm.mid.core.framework.page.DataResultVO
	 * @UpdateRemark [1][2019-02-21] [张现超][获取升级版本号]
	 */
	@RequestMapping(value = "/getVerId.do", method = { RequestMethod.POST })
	@ResponseBody
	public DataResultVO getVerId() throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取升级版本号成功");
        try {
            Long verId = this.sysAppVerCfgService.getVerId();
            result.setData(verId);
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "getVerId", "获取升级版本号异常");
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("获取升级版本号异常");
        }
        return result;
	}

	/**
	 * 添加最新更新版本到缓存
	 * @param opTypCd 客户端类型
	 * @param sysCd 系统代码
	 */
	private void setAppMaxVerRule(String opTypCd, String sysCd) throws BaseException{
		try {
            StringBuffer strRule=new StringBuffer("");
            String strMaxInt="0";

            Integer maxVerId=this.sysAppVerCfgService.selectMaxVerId(opTypCd,sysCd);
			if(null != maxVerId){
                strMaxInt=maxVerId.toString();
				List<SysAppVerRuleDTO> sysAppVerRuleDTOList=this.sysAppVerCfgService.selectMaxVerList(maxVerId,opTypCd,sysCd);
				if(CollectionUtils.isNotEmpty(sysAppVerRuleDTOList)){
					for (SysAppVerRuleDTO ruleDTO : sysAppVerRuleDTOList) {
						if(null != ruleDTO && StringUtils.isNotEmpty(ruleDTO.getVerRule())){
							strRule.append(ruleDTO.getVerRule()).append(",");
						}
					}
				}
			}
            String upgradesubkey = PropertiesCacheUtils.getProperty(UpgradeConstant.UPGRADE_VER_CACHE_MID_KEY);

            String key=sysCd + upgradesubkey + opTypCd+":MAXVERID";
            BaseLogUtils.info(logger, "setAppMaxVerRule", "KEY:" +key+",value:"+maxVerId);

            //设置老缓存
            this.cacheService.add(key, strMaxInt, CacheConstant.CACHE_OPERATION_REMOTE);
            //设置集群缓存
            this.userRedisService.set(key, strMaxInt);

            key=sysCd + upgradesubkey + opTypCd+":MAXVERRULE";
            BaseLogUtils.info(logger, "setAppMaxVerRule", "KEY:" +key+",value:"+strRule.toString());
            //设置老缓存
            this.cacheService.add(key, strRule.toString(), CacheConstant.CACHE_OPERATION_REMOTE);
            //设置集群缓存
            this.userRedisService.set(key, strRule.toString());
		}catch(BaseException ex) {
			BaseLogUtils.info(logger, "addUpgradeVersToCache", "更新最新版本到缓存错误" + ex.getMessage(), ex);
		}catch(Exception ex) {
			BaseLogUtils.error(logger, "addUpgradeVersToCache", "更新最新版本到缓存错误" + ex.getMessage(), ex);
		}
	}
}

